<template>
	<e-popup :show="show" mode="bottom" round="20rpx" @close="emit('close')">
		<view class=" e-p-l-30 e-p-r-30 e-rela">
			<view class="global-address-mask e-flex-xy-center" v-show="loading">
				<e-loading-icon :show="loading"></e-loading-icon>
			</view>
			<view class="e-flex-xy-center e-p-t-10 e-m-b-30">
				<text>{{ $t('user.选择所在地区') }}</text>
				<!-- <image src="/static/img/pay/close.png" class="img-36 components-pay-address__close" @tap="show=false"></image> -->
			</view>
			<view class="e-flex e-p-t-22 e-p-b-22">
				<view class="mar-r-72" @tap="swiperIndex = 0" :class="{ 'c-red': swiperIndex === 0 && provincesName }">
					{{ provincesName || $t('common.请选择') }}
				</view>
				<view v-show="provincesName && cityShow" class="mar-r-72" :class="{ 'c-red': swiperIndex === 1 }"
					@tap="swiperIndex = 1">
					{{ cityName || $t('common.请选择') }}
				</view>
				<view v-show="cityName && areaShow" class="mar-r-72" :class="{ 'c-red': swiperIndex === 2 }"
					@tap="swiperIndex = 2">
					{{ areaName || $t('common.请选择') }}
				</view>
				<view v-show="areaName && townShow" :class="{ 'c-red': swiperIndex === 3 }" @tap="swiperIndex = 3">
					{{ townName || $t('common.请选择') }}
				</view>
			</view>
			<view class="global-address ">
				<view class="global-address-item" v-for="(item, index) in columns" :key="index"
					v-show="swiperIndex === index">
					<scroll-view scroll-y>
						<view class="e-flex e-m-t-40 e-flex e-flex-between"
							:class="[modelValue[index] === items.id ? 'c-red' : 'c-34']" v-for="(items, indexs) in item"
							:key="items.id" @tap="selectAddress(index, items.id)">
							<text>{{ items.name }}</text>
							<view v-show="modelValue[index] === items.id">
								<app-image :size="['26rpx']" src="user/success_red.png"
									 />
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
			<!-- <view class="e-p-l-30 e-p-r-30 e-m-b-20 e-m-t-60">
				<e-button size="large"  type="primary" shape="circle" :text="$t('common.确定')" @click="$emit('close')"></e-button>
			</view> -->
		</view>
	</e-popup>
</template>
<script lang="ts">
	import { defineComponent } from 'vue'
	export default defineComponent({
		name: "globalAddress",
	})
</script>
<script setup lang="ts">
	import { ref, watch, computed, nextTick } from 'vue'
	import { getProvinceList, getProvinceChildList } from '@/common/request/api'
	import type { addressItem } from '@/common/request/api'

	const props = withDefaults(defineProps<{
		modelValue : number[],
		show : boolean,
		primary : string,
		currentCountryCode : string
	}>(), {})

	const emit = defineEmits(['update:modelValue', 'textChange', 'update:show', 'close'])

	const loading = ref(false)
	const columns = ref<[addressItem[], addressItem[], addressItem[], addressItem[]]>([[], [], [], []])
	const cityList = new Map<number, addressItem[]>([])
	const areaList = new Map<number, addressItem[]>([])
	const townList = new Map<number, addressItem[]>([])
	const swiperIndex = ref(0)
	const townShow = ref(false)

	watch(() => props.modelValue, (val) => {
		if (val.length === 0) {
			swiperIndex.value = 0
		}
	})
	const provincesName = computed(() => columns.value[0].find(item => item.id === props.modelValue[0])?.name || '')
	const cityName = computed(() => {
		let arr = columns.value[1] || []
		return arr.find(item => item.id === props.modelValue[1])?.name || ''
	})
	const areaName = computed(() => {
		let arr = columns.value[2] || []
		return arr.find(item => item.id === props.modelValue[2])?.name || ''
	})
	const townName = computed(() => {
		let arr = columns.value[3] || []
		return arr.find(item => item.id === props.modelValue[3])?.name || ''
	})

	const addrText = computed(() => `${provincesName.value} ${cityName.value} ${areaName.value} ${townName.value}`)
	const cityShow = computed(() => (columns.value[1] || []).length > 0)
	const areaShow = computed(() => (columns.value[2] || []).length > 0)


	const init = (isGet = true) => {
		swiperIndex.value = 0
		getProvinceList({ countryCode: props.currentCountryCode }).then(res => {
			columns.value.splice(0, 1, res.data)

			if (isGet) {
				getProvinceChild(res.data[0].id, 0)
			} else {
				getProvinceChild(props.modelValue[0], 0, false)
				getProvinceChild(props.modelValue[1], 1)
				getProvinceChild(props.modelValue[2], 2)
				if (props.modelValue[3]) {
					townShow.value = true
				}
			}

		})
	}
	const getProvinceChild = (id : number, index : number, isGet = true, callBack ?: Function) => {
		if (!id) return
		loading.value = true
		getProvinceChildList(id).then(res => {
			columns.value.splice(index + 1, 1, [])

			loading.value = false

			if (res.data.length) {
				if (index === 0) {
					cityList.set(id, res.data)

					isGet && getProvinceChild(res.data[0].id, 1)
				} else if (index === 1) {
					areaList.set(id, res.data)
					isGet && getProvinceChild(res.data[0].id, 2)
				} else {
					townList.set(id, res.data)
				}
				columns.value.splice(index + 1, 1, res.data)
			} else {
				callBack && callBack(index)
			}


		})
	}
	const selectAddress = (columnIndex : number, values : number) => {

		let addrIds = [...props.modelValue]
		addrIds.splice(columnIndex, 1, values)
		changeHandler({
			columnIndex,
			values
		}, addrIds)
		if (columnIndex === 3) {
			emit('update:modelValue', addrIds)
			nextTick(() => {
				emit('textChange', addrText.value)
				
			})
			emit('update:show',false)
			emit('close')
			return
		} else if (columnIndex === 2) {
			if (columns.value[3]?.length) {
				townShow.value = true
			} else {
				townShow.value = false
				emit('update:show',false)
				emit('close')
				return
			}
			
		}
		swiperIndex.value = columnIndex + 1


	}
	const changeHandler = (e : {
		columnIndex : number
		values : number
	}, addrIds : number[]) => {
		const { columnIndex, values } = e;
		if (props.modelValue[columnIndex] === values) return
		if (columnIndex !== 3) {
			// 清除addrIds中索引大于columnIndex的数据
			// 如用户选择了市,那么就会将addrIds中的区和街道的id数据清除
			if (addrIds[columnIndex + 1]) {
				for (let i = 4; i > columnIndex; i--) {
					addrIds.splice(i, 1)
				}

			}
			emit('update:modelValue', addrIds)
			nextTick(() => {
				emit('textChange', addrText.value)
			})
			let data : addressItem[] | undefined
			if (columnIndex === 0) {
				data = cityList.get(values)
			} else if (columnIndex === 1) {
				data = areaList.get(values)
			} else {
				data = townList.get(values)
			}
			if (data) {
				columns.value.splice(columnIndex + 1, 1, data)

				if (columnIndex === 0) {
					let area = areaList.get(data[0].id) || []
					columns.value.splice(2, 1, area)
				} else if (columnIndex === 1) {
					let town = townList.get(data[0].id) || []
					columns.value.splice(3, 1, town)
				}
			} else {
				getProvinceChild(values, columnIndex, true, (index : number) => {
					emit('update:show',false)
					if (index < 2) {
						swiperIndex.value = swiperIndex.value - 1
					}

				})
			}
		}
	}

	defineExpose({
		init
	})
</script>

<style lang="scss" scoped>
	.mar-r-72 {
		margin-right: 72rpx;
	}

	.global-address-mask {
		position: absolute;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		z-index: $z-index-normal;
	}

	.global-address {
		width: 100%;
		height: 800rpx;
		position: relative;

		.global-address-item {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;

			scroll-view {
				height: 800rpx;
			}
		}
	}
</style>